AddCSLuaFile( "cl_init.lua" )
     AddCSLuaFile( "shared.lua" )
      
     include('shared.lua')
	 
	function antlionCount()
		local hcs = ents.FindByClass("colonies_antlion")
		return #hcs
	end
	 
	function ENT:SpawnFunction( ply, tr)
		if antlionCount() < GetConVarNumber("co_antlion_max") then
			local SpawnPos = tr.HitPos
			local ent = ents.Create( "colonies_antlion" )
			ent:SetPos( SpawnPos )
			ent:Spawn()
			return ent
		end
		return nil
	end

    function ENT:Initialize()

		
		//Init genetics
		Genetics = {}

		Genetics.Slot1name = ""
		Genetics.Slot1magn = 0

		Genetics.Slot2name = ""
		Genetics.Slot2magn = 0

		Genetics.Slot3name = ""
		Genetics.Slot3magn = 0

		Genetics.Slot4name = ""
		Genetics.Slot4magn = 0

		Genetics.Slot5name = ""
		Genetics.Slot5magn = 0
		

		//VERY IMPORTANT TO NEW UPDATE		
		self.PriorityLevel = 0
		//PriorityLevel 0 = Idle
		//PriorityLevel 1 = Normal wandering
		//PriorityLevel 2 = Journey
		//PriorityLevel 3 = Food
		//PriorityLevel 4 = Fight / Hunt

		self.health = 50
		self.maxhealth = 50
		self.reactiontime = 1
		ReactionTime = self.reactiontime

		self.born = math.Round(CurTime())
		self.hunger = 0
		
		self.lipids = 5

		self.glucose = 25

		self.protein = 20

		criticalhunger = 75

		self.totalenergy = self.protein + self.lipids + self.glucose

		self.name = coloniesnames[math.random(1,#coloniesnames)]
		self.wanderdistance = 200
		self.Speed = 1
		self.minuswanderdistance = -200
		self.journeydistancex = 3200
		self.journeydistancey = 3200
		self.nofood = true
		self.nojourney = true
		//Time it takes to produce egg.
		self.gestation = 25
		//Amount hunger increases each second; influenced by AGE.
		self.hungerinc = 2
		//Amount hungerinc is modified; influenced by HUNGER (greater hunger = lower mod)
		self.hungerincmod = 1

		//Percentage of health left before fleeing
		self.Fleehealth = 40

		//Self (haha) explanatory
		self.lifespan = 600
		self.comeofage = 25
		self.adult = 100
		self.elderly = 300
		self.lastegg = math.Round(CurTime()) + self.comeofage + 1

		//Likelyhood to wander. Higher = less likely.
		self.wanderchance = 5
		//How hungry they can be before dying
		self.hungerthreshold = 100
		//How hungry they can be before they start to look for food
		self.hungry = 25

		self.searchradius = 1024
		self.fertility = 5

		self.growthspeed = 0.2

		self.temperature = 1
		
		//NO PARAMETERS THAT CAN BE MODIFIED BY GENETICS SHOULD BE BELOW THIS LINE.
		
		local crab = ents.Create("npc_antlion")
		self.crab = crab

		Selfcrab = self.crab

		self.crab.CombatMode = false
		self.crab.Currenttarget = nil
		self.crab.Currenttargettype = nil
		self.crab.alterntarget = nil

		self.crab.IsGlobal = 1
		
		//if not self.FromEgg then //PrintMessage(HUD_PRINTTALK,"New crab") else PrintMessage(HUD_PRINTTALK,"From egg") end
		//if not self.FromEgg then self.Entity:RandomizeGeneticsOnSpawn() else self.Entity:GeneticsFromEgg() end
		
		if not self.FromEgg then
			self.lipids = 50

			self.glucose = 50

			self.protein = 50
		end

		self.chosenmelon = nil
		
		//self.Speed = 1
		crab:SetPos(self.Entity:GetPos())
		crab:Spawn()
		crab:Activate()

		self.crab:SetNWString("HCname",self.name)
		self.crab:SetNWBool("HC",true)
		
		--set colour
		self.crab:SetColor(220,0,200,255)
		
		
		--setup disposition
		if GetConVarNumber("co_antlion_hateplayers") == 0 then
			self.crab:AddRelationship("player D_NU 999")
		end
				
			self.crab:SetHealth(self.health)
			self.crab:SetMaxHealth(self.health)

			//PrintMessage(HUD_PRINTTALK,"Health: "..health)

			
		self.crab:AddRelationship("npc_headcrab D_NU 999")
		self.crab:AddRelationship("npc_headcrab_fast D_NU 999")
		self.crab:AddRelationship("npc_headcrab_black D_NU 999")

		Currenttime = (math.Round(CurTime() * 100)) / 100

		Currentsecond = math.Round(CurTime())
		
		self.crab.NextReaction = Currenttime
		self.crab.NextOne = Currenttime

			self.Entity:ThinkonOne()
			self.Entity:ThinkonReaction()

		//These globals are for the antlion's combat code. Fyi, I couldn't refer to self - it was not available within the takedamage hook.
		antlion = self.Entity

		Foundtarget = false
		SearchRadius = self.searchradius
			 
    end

    function table.Random2(tab)  
        local t = table.Copy(tab)  
        return function()  
            if #t == 0 then  
                return  
            end   
           return table.remove(t, math.random(1, #t))  
        end  
    end  


	function ENT:RandomizeGeneticsOnSpawn()
	local r = table.Random2(headcrabgenes)

        Genetics.Slot1name = r() 
	Genetics.Slot1magn = math.Rand(0.1,2)

        Genetics.Slot2name = r() 
	Genetics.Slot2magn = math.Rand(0.1,2)

        Genetics.Slot3name = r() 
	Genetics.Slot3magn = math.Rand(0.1,2)

        Genetics.Slot4name = r() 
	Genetics.Slot4magn = math.Rand(0.1,2)

        Genetics.Slot5name = r() 
	Genetics.Slot5magn = math.Rand(0.1,2)

	self.Entity:DeployGenetics()
	end

	function ENT:DeployGenetics()

	for i=1,5 do

	PrintMessage(HUD_PRINTTALK,"Name: "..Genetics["Slot"..i.."name"].." ...Magnitude: "..Genetics["Slot"..i.."magn"])

	if Genetics["Slot"..i.."name"] == "Mercury" then
		//self.Speed = self.Speed * 1 + Genetics["Slot"..i.."magn"]
	end

	if Genetics["Slot"..i.."name"] == "Brute" then
		
		local magnitude = Genetics["Slot"..i.."magn"] + 1
		self.health = self.health+100*magnitude
		self.maxhealth = self.health
	end

	if Genetics["Slot"..i.."name"] == "Tank" then
		local magnitude = Genetics["Slot"..i.."magn"] + 1
		//self.crab:SetHealth(health+100*magnitude*magnitude)
		self.health = self.health+100*magnitude*magnitude
		self.maxhealth = self.health
	end

	if Genetics["Slot"..i.."name"] == "Spartan" then
		self.Fleehealth = 0
	end

	if Genetics["Slot"..i.."name"] == "Unyielding" then
		self.Fleehealth = 40 - Genetics["Slot"..i.."magn"]*10
	end

	if Genetics["Slot"..i.."name"] == "Pusillanimous" then
		self.Fleehealth = 50 + Genetics["Slot"..i.."magn"]*10
	end

	if Genetics["Slot"..i.."name"] == "Hotwire" then
		self.reactiontime = 1.05 - Genetics["Slot"..i.."magn"]/2
		ReactionTime = self.reactiontime
		//ReactionTime = 0.1
	end

	if Genetics["Slot"..i.."name"] == "Slowpoke" then
		self.reactiontime = 1 + Genetics["Slot"..i.."magn"]
		ReactionTime = self.reactiontime
		//ReactionTime = 3
	end
	
	if Genetics["Slot"..i.."name"] == "Fangs" then
		//self.crab.IsGlobal = 5
	end

	end

	/*
	antlion genes:
	A double star (**) in front of the gene means it has not been coded. However, most of these are elementary.
	I'd prefer if you didn't code them yourself; when I release updates, you'll lose your progress unless you know what you're doing.
	**	"Mercury", //Extra speed
		"Brute", //More health
		"Tank", //Just much higher health
		"Spartan", //Never flees
		"Unyielding", //Takes more damage before fleeing
		"Pusillanimous", //Takes less damage before fleeing
	**	"Voracious", //Gets hungry more quickly
	**	"Fangs", //Greater damage
	**	"Efficient", //Less hunger
	**	"Strong", //Relatively high health and damage
	**	"Survivor", //High hunger threshold
		"Hotwire", //Fast reaction times
		"Slowpoke", //Slow reaction times
	**	"Mother", //High fertility rate
	**	"Witch", //Passive at first, but can become enraged
	**	"Hyperactive", //More prone to wandering
	**	"Elephant", //Greater lifespan
	**	"Mayfly", //Short lifespan
	**	"Explorer" //Wanders further, more prone to journeys.
	**	"Panacea", //Fast healing rate
	**	"Asbestos", //Fire resistant
	*/
	end

	function ENT:GeneticsFromEgg()	

        Genetics.Slot1name = self.Slot1n
	Genetics.Slot1magn = self.Slot1m

        Genetics.Slot2name = self.Slot2n
	Genetics.Slot2magn = self.Slot2m

        Genetics.Slot3name = self.Slot3n
	Genetics.Slot3magn = self.Slot3m

        Genetics.Slot4name = self.Slot4n
	Genetics.Slot4magn = self.Slot4m

        Genetics.Slot5name = self.Slot5n
	Genetics.Slot5magn = self.Slot5m
	
	self.Entity:DeployGenetics()
	end
     
     function ENT:OnTakeDamage(dmg)
    
     end
	 
	    
	/*---------------------------------------------------------
	Name: OnRemove
	Desc: Called just before entity is deleted
	//-------------------------------------------------------*/
	function ENT:OnRemove()
		-- kill the npc
		if ValidEntity(self.crab) == true then
			PrintMessage(HUD_PRINTTALK," antlion "..self.name.." removed.")
			self.crab:Remove(0)
		end
	end

	function ENT:Idle()

	//PrintMessage(HUD_PRINTTALK,"IDLE")

	self.crab:SetSchedule(3)
	end


	function ENT:Journey()

		local jposx = math.Rand(-3200,3200)
		local jposy = math.Rand(-3200,3200)

		self.crab:SetLastPosition(self.crab:GetPos()+Vector(jposx,jposy,0))
		self.crab:SetSchedule(71)

		//PrintMessage(HUD_PRINTTALK,"JOURNEY")

		/*
		local differencex = math.random(-320,320)
		local differencey = math.random(-320,320)

		local journeydistancex = 3200
		local journeydistancey = 3200

		local choicex = math.random(1,2)
		if choicex == 2 then journeydistancex = -3200 end

		local choicey = math.random(1,2)
		if choicey == 2 then journeydistancey = -3200 end

		//local posx = (journeydistancex+differencex)
		//local posy = (journeydistancey+differencey)
		*/
		
	end

	function ENT:Wander()
		local posx = math.random(self.minuswanderdistance,self.wanderdistance)
		local posy = math.random(self.minuswanderdistance,self.wanderdistance)
		self.crab:SetLastPosition(self.crab:GetPos()+Vector(posx,posy,0))
		self.crab:SetSchedule(71)
		self.Entity:Respirate((math.sqrt(math.pow(posx,2)+math.pow(posy,2)))/100)

		//PrintMessage(HUD_PRINTTALK,self.name.." is wandering")
	end

	function ENT:SearchForFood()
	self.nofood = true

		//PrintMessage(HUD_PRINTTALK,self.name.." is searching for food.")

		--find corpses in x radius and eat
		local sphents = ents.FindInSphere(self.crab:GetPos(),32)
		for i, thent in ipairs(sphents) do
			if thent:GetClass() == "prop_ragdoll" then
			if thent:GetModel() == "models/headcrabclassic.mdl" or thent:GetModel() == "models/headcrab.mdl" or thent:GetModel() == "models/headcrabblack.mdl" then
				if self.hunger > 30 then
					thent:Remove()
					self.hunger = self.hunger - 100
				end
			end
			end
		end
		
		--find w'melons in x radius and goto (if we don't already have a valid w'mn, or our w'melon is too far away)
		if ValidEntity(self.watermelon) == false or self.crab:GetPos():Distance(self.watermelon:GetPos()) > 32 then
			local sphentseat = ents.FindInSphere(self.crab:GetPos(),self.searchradius)
			local closest = 1024
			for i, thenteat in pairs(sphentseat) do
			//for i, thenteat in ipairs(sphentseat) do
				if not thenteat:IsNPC() then
				if thenteat:GetModel() == "models/headcrabclassic.mdl" or thenteat:GetModel() == "models/headcrab.mdl" or thenteat:GetModel() == "models/headcrabblack.mdl" && thenteat:GetPos():Distance(self.crab:GetPos()) < closest && self.hunger > self.hungry then
					self.crab:SetLastPosition(thenteat:GetPos()+Vector(0,0,0))
					self.watermelon = theenteat
					self.crab:SetSchedule(71)
					self.nofood = false

					if not self.crab.CombatMode then
						self.crab:AddRelationship("npc_headcrab D_NU 999")
						self.crab:AddRelationship("npc_headcrab_fast D_NU 999")
						self.crab:AddRelationship("npc_headcrab_black D_NU 999")
					end
					closest = thenteat:GetPos():Distance(self.crab:GetPos())
					break
				//elseif thenteat:GetClass() != "colonies_watermelon" || thenteat:GetPos():Distance(self.crab:GetPos()) >= closest || self.hunger <= self.hungry then
				end
				end


			end

			if self.nofood then
				
				self.crab:AddRelationship("npc_headcrab D_HT 999")
				self.crab:AddRelationship("npc_headcrab_fast D_HT 999")
				self.crab:AddRelationship("npc_headcrab_black D_HT 999")
				
				//PrintMessage(HUD_PRINTTALK,self.name.." couldn't find food. Now hostile.")
			local sphentseat = ents.FindInSphere(self.crab:GetPos(),self.searchradius)
				local closest = 1024
				for i, thenteat in pairs(sphentseat) do
					if not thenteat:GetModel() == "models/headcrabclassic.mdl" and not thenteat:GetModel() == "models/headcrab.mdl" and not thenteat:GetModel() == "models/headcrabblack.mdl" then
						local journey = math.random(1,self.wanderchance)
						if journey <= 2 then self.Entity:Wander() end
					end
				end
					
			end
		end
		


	end

function ENT:Fight()
	
	Foundtarget = false

	self.crab:SetSchedule(5) //Not sure if this actually does anything.

	//Note: this function scans the surrounding area for enemies.
		//PrintMessage(HUD_PRINTTALK,self.name.." is fighting.")

		local sphentseat = ents.FindInSphere(self.crab:GetPos(),self.searchradius)
		for i, thenteat in pairs(sphentseat) do
		//local en
		//for i, #sphentseat do
				//PrintMessage(HUD_PRINTTALK,"Data: "..i.." ... "..thenteat)
				//if 
			if thenteat:GetPos():Distance(self.crab:GetPos()) < self.searchradius then
				if thenteat:IsPlayer() or thenteat:IsNPC() then
					//PrintMessage(HUD_PRINTTALK,"Data: "..i)
					//PrintMessage(HUD_PRINTTALK,self.name..": What is it?: "..thenteat:GetClass())

					if thenteat == self.crab.Currenttarget then
						self.crab.CombatMode = true
						Foundtarget = true
						self.Entity:AttackTarget()
					end
					
					if thenteat:GetClass() == self.crab.Currenttargettype and thenteat ~= self.crab.Currenttarget then
						self.crab.alterntarget = thenteat
						//PrintMessage(HUD_PRINTTALK,self.name..": Found an alternative target")
					end

					if thenteat:GetClass() == "npc_antlion" then
						//if thenteat:IsValid() and thenteat ~= self.crab and Foundtarget and thenteat.Currenttarget == nil then
						if thenteat:IsValid() and thenteat ~= self.crab and Foundtarget and not thenteat.Combatmode then
							if thenteat:GetPos():Distance(self.crab.Currenttarget:GetPos()) < self.searchradius then
								thenteat.CombatMode = true
								thenteat.Currenttarget = self.crab.Currenttarget
								thenteat.Currenttargettype = self.crab.Currenttargettype
								if self.crab:IsValid() then PrintMessage(HUD_PRINTTALK,self.name..": Come and help me!") else PrintMessage(HUD_PRINTTALK,"...Come and help me!") end
							end
						end
					end

				end
			end
				
		end

		if not Foundtarget then
			if self.crab.alterntarget ~= nil then
			self.crab.Currenttarget = self.crab.alterntarget
			PrintMessage(HUD_PRINTTALK,self.name..": Switching targets")
			else
			self.Entity:TargetLost()
			//PrintMessage(HUD_PRINTTALK,self.name..": Target cannot be seen")
			end
		end

end

	function ENT:AttackTarget()
		self.Entity:Respirate(2)
		self.crab:AddEntityRelationship(self.crab.Currenttarget, D_HT, 99)
		self.crab:SetEnemy(self.crab.Currenttarget)					
		self.crab:AddRelationship(self.crab.Currenttargettype, D_HT, 98)
		//PrintMessage(HUD_PRINTTALK,self.name..": attacking!")
		if timer.IsTimer("Lostmemory"..self.name) then timer.Destroy("Lostmemory"..self.name) end
	end
 
	function ENT:TargetLost()
		
		//PrintMessage(HUD_PRINTTALK,self.name..": Losing target...")
		if not timer.IsTimer("Lostmemory"..self.name) then
			timer.Create("Lostmemory"..self.name, 5, 1, function()
			//timer.Simple(5, function()
				if self.crab.Currenttarget:IsValid() then self.crab:AddEntityRelationship(self.crab.Currenttarget, D_NU, 99) end
				if self.crab.Currenttarget:IsValid() then self.crab:AddRelationship(self.crab.Currenttargettype, D_NU, 98) end
				self.crab.CombatMode = false
				self.crab.Currenttarget = nil
				self.crab.Currenttargettype = nil
				Foundtarget = false
				self.crab.alterntarget = nil
				//PrintMessage(HUD_PRINTTALK,self.name..": Target lost")
			end)
		end
		
	end


	function ENT:Ketosis(joules)
		//if self.lipids >= joules then
		//	self.lipids = self.lipids - joules
		//	self.glucose = self.glucose + joules * 2
		//end
		if self.lipids >= joules then 
			self.lipids = self.lipids - joules
			//self.glucose = self.glucose + joules * 2
			self.glucose = self.glucose + joules
		elseif self.lipids < joules and self.lipids * 2 > joules then
			local fat = self.lipids
			for i=0, fat do
			if i * 2 > joules then
				self.lipids = self.lipids - i
				//self.glucose = self.glucose + i * 2
				self.glucose = self.glucose + i
			end
			end
		elseif self.lipids * 2 < joules then
			self.lipids = 0
			//self.glucose = self.glucose + self.lipids * 2 //Not sure if this works
			self.glucose = self.glucose + self.lipids //Not sure if this works
			//local remainder = joules - self.lipids * 2
			local remainder = joules - self.lipids
			self.Entity:MetaboliseProteins(remainder)
		end
	end

	function ENT:Respirate(joules)
			if self.protein > 10 then self.protein = self.protein - self.growthspeed end
		if self.glucose >= joules then 
			self.glucose = self.glucose - joules
		elseif self.glucose > 0 and self.glucose < joules then
			local remainder = joules - self.glucose
			self.Entity:Ketosis(remainder)
			self.glucose = 0
		elseif self.glucose == 0 then
			self.Entity:Ketosis(joules)
		end
	end

	function ENT:MetaboliseProteins(joules)
		if self.protein >= joules then
			self.protein = self.protein - joules
			//self.glucose = self.glucose + joules
		else
		self.Entity:Die()
		end
	end

	function ENT:ThinkonReaction()

		self.crab.NextReaction = Currenttime + self.reactiontime

		//-----------------------Self-defense--------------------------
		//-------------------------code--------------------------------

	//That is, if the antlion has been told by another it's been attacked, and it's not currently engaged in fighting, then it will attack.
	
		if self.crab.CombatMode then
		self.Entity:Fight()
		self.Entity:Respirate(0.5) //Adrenaline causes faster metabolism, right?
		return
		else

		//This is the new Priority-Based system upon which the animal's AI is based. V IMPORTANT

		//-----------------------DECISION------------------------------
		//------------------------CODE---------------------------------
		
		local relocate = math.random(1,self.wanderchance)				
		if relocate <= 2 and self.PriorityLevel < 2 then self.PriorityLevel = 1 end

		local journey = math.random(1,10)
		if journey <= 1 and self.PriorityLevel < 3 then self.PriorityLevel = 2 end

		if self.glucose < self.hungry then self.PriorityLevel = 3 end


		//-----------------------RESET------------------------------
		//------------------------CODE------------------------------

		if self.PriorityLevel == 3 and self.glucose >= self.hungry then self.PriorityLevel = 2 end

		if self.PriorityLevel == 2 and journey > 1 then self.PriorityLevel = 1 end

		if self.PriorityLevel == 1 and relocate > 2 then self.PriorityLevel = 0 end

		//-----------------------BEHAVIOUR------------------------------
		//------------------------CODE----------------------------------
				
		if self.PriorityLevel == 0 then self.Entity:Idle() end

		if self.PriorityLevel == 1 then self.Entity:Wander() end

		if self.PriorityLevel == 2 then self.Entity:Journey() end

		if self.PriorityLevel == 3 then self.Entity:SearchForFood() end

		end
	end

	function ENT:ThinkonOne()

		Currentsecond = math.Round(CurTime())

		self.crab.NextOne = Currentsecond + 1

		self.Entity:Respirate(self.temperature) //Maintaining body temperature.

		//Store as fat
		if self.glucose > 60 then
			self.lipids = self.lipids + self.glucose - 60
			self.glucose = 60
		end

		//Get rid of excess protein
		if self.protein > 60 then
			self.protein = self.protein - 1
		end
		
		--Is the antlion still alive?
		if ValidEntity(self.crab) == false then
			self.Entity:Die()
			return
		end

		if math.Round(CurTime()) > self.born + self.lifespan then
			//self:Remove()
			if GetConVarNumber("co_printevents") == 1 then
				PrintMessage(HUD_PRINTTALK," antlion "..self.name.." died of Old Age")
				if math.random(1,8) > 3 then
					local melonseed = ents.Create("colonies_watermelonseed")
					//undo.ReplaceEntity(self.Entity,melonseed)		
					melonseed:SetPos(self.Entity:GetPos()+Vector(0,0,0))
					melonseed:Spawn()
					if GetConVarNumber("co_printevents") == 1 then
						PrintMessage(HUD_PRINTTALK," antlion "..self.name.." has dropped a seed")
					end
				end
			end
		self.Entity:Die()
		end

		local age = math.Round(CurTime()) - self.born

		// Age modifications
		if age > self.comeofage then
			self.growthspeed = 0.3
			self.gestation = 50
			self.crab:SetColor(255,255,255,255)
		end

		if age > self.adult then
			self.growthspeed = 0.1
			self.gestation = 100
		end

		if age > self.elderly then
			self.growthspeed = 0.05
			self.gestation = 200
		end
		
		local numberofeggs = math.random(1,self.fertility)
		if self.glucose > 5 * numberofeggs and self.lipids > 25 * numberofeggs and self.protein > 15 * numberofeggs then
		if math.Round(CurTime()) > self.lastegg + self.gestation and antlionCount() <= GetConVarNumber("co_antlion_max") then
			for eggs=1, numberofeggs do
			local egg = ents.Create("colonies_antlionegg")
			egg:SetPos(self.crab:GetPos()+Vector(0,0,15))

				egg.FromCrab = true

				egg.Slot1n = Genetics.Slot1name
				egg.Slot1m = Genetics.Slot1magn


				egg.Slot2n = Genetics.Slot2name
				egg.Slot2m = Genetics.Slot2magn


				egg.Slot3n = Genetics.Slot3name
				egg.Slot3m = Genetics.Slot3magn


				egg.Slot4n = Genetics.Slot4name
				egg.Slot4m = Genetics.Slot4magn


				egg.Slot5n = Genetics.Slot5name
				egg.Slot5m = Genetics.Slot5magn


			egg:Spawn()

		self.glucose = self.glucose - 5 * numberofeggs
		self.lipids = self.lipids - 25 * numberofeggs
		self.protein = self.protein - 15 * numberofeggs

			end
			self.lastegg = math.Round(CurTime())
		end
		end
	
		//self.hunger = self.hunger + math.Round((self.hungerinc * self.hungerincmod))
		//self.crab:SetNWInt("HChunger",self.hunger)

		self.crab:SetNWInt("HCage",math.Round(CurTime())-self.born)

		self.crab:SetNWInt("HCEnergy",self.totalenergy)

		self.crab:SetNWInt("HCGlucose",math.Round(self.glucose))
		self.crab:SetNWInt("HCLipids",math.Round(self.lipids))
		self.crab:SetNWInt("HCProtein",math.Round(self.protein))

		//if self.hunger >= self.hungerthreshold then
		if self.totalenergy <= 10 then
			if GetConVarNumber("co_printevents") == 1 then
				PrintMessage(HUD_PRINTTALK,"antlion "..self.name.." died of Hunger :'(")
			end
			//self:Remove()
			self.Entity:Die()
		end


		if self.hunger < 0 then
			self.hunger = 0
		end
	end

	function ENT:Die()
		PrintMessage(HUD_PRINTTALK," antlion "..self.name.." died.")
		local ragdoll = ents.Create("prop_ragdoll")
		ragdoll:SetModel("models/antlion.mdl")
		ragdoll:SetPos(self.crab:GetPos()+Vector(0,0,1))
		ragdoll:SetAngles(self.crab:GetAngles())
		ragdoll:SetCollisionGroup(COLLISION_GROUP_DEBRIS)

		ragdoll:Spawn()
		self:Remove()

			timer.Create("Delete Ragdoll Delay ", 2, 1, function()
    			timer.Create("Delete Ragdoll ", 0.02, 256, function()  
      
       				local r,g,b,a = ragdoll:GetColor()  
        			if a <= 0 then  
        				ragdoll:Remove()
        			else  
					Alpha1 = math.Approach(a, 0, 1)  
					ragdoll:SetColor(r, g, b, Alpha1)  
       				end       
   			end)
			end)

	end
    
	function ENT:Think()

	self.totalenergy = math.Round(self.protein + self.lipids + self.glucose)

	if self.Entity:IsValid() and self.crab:IsValid() then
	
	if self.crab:Health() < 1 then

		PrintMessage(HUD_PRINTTALK,"Headcrab was killed...")
		//self.Entity:Die()
	end

	Currenttime = (math.Round(CurTime() * 100)) / 100

	Currentsecond = math.Round(CurTime())
	
	//PrintMessage(HUD_PRINTTALK,"Currenttime: "..Currenttime)

	//PrintMessage(HUD_PRINTTALK,"Currentsecond: "..Currentsecond)

	//PrintMessage(HUD_PRINTTALK,"self.crab.NextReaction: "..self.crab.NextReaction)
	
	//PrintMessage(HUD_PRINTTALK,"Reactiontime: "..self.reactiontime)
	
	//PrintMessage(HUD_PRINTTALK,"self.crab.NextOne: "..self.NextOne)
	
	if Currenttime >= self.crab.NextOne then self.Entity:ThinkonOne() end

	if Currenttime >= self.crab.NextReaction then self.Entity:ThinkonReaction() end
	end



		/*
		if self.hunger > 75 and self.food == nil then
		else
		self.crab:AddRelationship("npc_headcrab D_NU 999")
		self.crab:AddRelationship("npc_headcrab_fast D_NU 999")
		self.crab:AddRelationship("npc_headcrab_black D_NU 999")
		end
		*/

		self.Entity:NextThink(Currenttime+0.001)
		//return true
	end

hook.Add("EntityTakeDamage","Entitytakedamage", function( ent, inflictor, attacker, amount, dmginfo )

	if ent == Selfcrab then
	
		ent.NextReaction = Currenttime + ReactionTime
		PrintMessage(HUD_PRINTTALK,"antlion was hit!")

		
			//PrintMessage(HUD_PRINTTALK,self.name.." reacted due to taking damage...")

			//PrintMessage(HUD_PRINTTALK,"Ent: "..ent:GetClass())
			//PrintMessage(HUD_PRINTTALK,"Attacker: "..attacker:GetClass())
			//PrintMessage(HUD_PRINTTALK,"Inflictor: "..inflictor:GetClass())

			local sphentseat = ents.FindInSphere(antlion:GetPos(),SearchRadius/2)
				for i, thenteat in ipairs(sphentseat) do
					if thenteat == attacker && thenteat:GetPos():Distance(antlion:GetPos()) < SearchRadius/2 and ent:IsValid() then
						if ent.Currenttarget == nil then
							timer.Create("React", ReactionTime, 1, function()
							ent.Currenttarget = attacker
							ent.Currenttargettype = attacker:GetClass()
							ent.CombatMode = true
							//PrintMessage(HUD_PRINTTALK,"TARGET LOCKED")
							//Headcrab:Fight(true,attacker)
							end)
						end
					end
					if thenteat:GetClass() == "npc_antlion" then
							if thenteat:IsValid() and thenteat ~= ent and not thenteat.Combatmode then
								if thenteat:GetPos():Distance(attacker:GetPos()) < SearchRadius /2 then
									timer.Create("React", thenteat.reactiontime, 1, function()
									thenteat.CombatMode = true
									thenteat.Currenttarget = attacker
									thenteat.Currenttargettype = attacker:GetClass()
									PrintMessage(HUD_PRINTTALK,"...Rushing to help!")
									end)
								end
							end
					end
				end

	end
end)
